package co.edu.usbcali.dataaccess.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import co.edu.usbcali.dataaccess.api.HibernateDaoImpl;
import co.edu.usbcali.modelo.Entradas;
import co.edu.usbcali.modelo.dto.EntradasDTO;


/**
 * A data access object (DAO) providing persistence and search support for
 * Entradas entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 *
 * @see lidis.Entradas
 */
@Scope("singleton")
@Repository("EntradasDAO")
public class EntradasDAO extends HibernateDaoImpl<Entradas, Long>
    implements IEntradasDAO {
    @SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(EntradasDAO.class);
    @Resource
    private SessionFactory sessionFactory;

    public static IEntradasDAO getFromApplicationContext(ApplicationContext ctx) {
        return (IEntradasDAO) ctx.getBean("EntradasDAO");
    }

	@SuppressWarnings("unchecked")
	@Override
	public Long existeEntrada(Entradas entrada) throws Exception {
		
		Long existe = 0L;
		try {
			Query query = getSession().getNamedQuery("existeEntrada");
			query.setParameter("pUrl", entrada.getUrl());
			query.setParameter("pCodUsu", entrada.getCodigoUsua());
			List<Long> cantA = query.list();

			if (cantA!=null&&cantA.size()!=0) {
				existe=cantA.get(0);
			}
			
			if(existe==0L){
				return 0L;
			}else{
				return existe;
			}
			
		} catch (Exception e) {
			throw e;
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<EntradasDTO> consultarFavoritosUsuario(Long codUsu)throws Exception {

		List<EntradasDTO> lista=null;
		
		try {
			Query query = getSession().getNamedQuery("consultaFavoritosUsuario");
			query.setParameter("pCodUsu", codUsu);
			query.setResultTransformer(Transformers.aliasToBean(EntradasDTO.class));
			lista= query.list();

		} catch (Exception e) {
			throw e;
		}
		
		return lista;
	}
}
